<script setup lang="ts">
import { loginAPI, tokenAPI, registerAPI, loginAPI1 } from '@/services/my'
import { registerAPIhou } from '@/services/my copy'

import type { mylogin } from '@/types/my'
import { ref, onMounted, computed } from 'vue'
import { myStore } from '@/stores'
import { useMemberStore } from '@/stores'

const userInfo = ref<any>({
  picAddress: '../../static/assets/img/海贼王_r.jpg',
  userName: '',
  mid: [],
})
const information = ref<any>({
  username: '',
  password: '',
  password1: '',
  email: '',
  phone: '',
  picAddress: '',
  gender: 1,
})
const usernameError = ref<any>('')
const passwordError = ref<any>('')
const flag = ref<any>(true)
const url = ref<any>('../../static/tabs/eye.png')
const bulr = (event: Event) => {
  console.log('2222222222222222')
  console.log(event.detail.value)

  information.value.phone = event.detail.value
  console.log(information.value.phone)
  // eslint-disable-next-line vue/return-in-computed-property
  usernameError.value = computed(() => {
    const reg = /^1[3456789]\d{9}$/

    if (information.value.phone.length === 0) {
      return '请填写手机号'
    } else if (information.value.phone.length > 11) {
      return '手机号长度不能超过11个字符'
    } else if (!reg.test(information.value.phone)) {
      return '手机号请输入规范格式，如数字字符'
    }
  })
}
const bulr1 = (event: Event) => {
  information.value.email = event.detail.value
  // eslint-disable-next-line vue/return-in-computed-property
  passwordError.value = computed(() => {
    const email =
      /^[A-Za-z0-9]+([-._][A-Za-z0-9]+)*@[A-Za-z0-9]+(-[A-Za-z0-9]+)*(\.[A-Za-z]{2,6}|[A-Za-z]{2,4}\.[A-Za-z]{2,3})$/

    if (information.value.email.length === 0) {
      return '请填写邮箱'
    } else if (information.value.email.length > 16) {
      return '邮箱长度不能超过16个字符'
    } else if (!email.test(information.value.email)) {
      return '邮箱请输入规范格式，字符数字即可'
    }
  })
}

// methods  q
function onName(event: Event) {
  console.log(event)
  information.value.username = (event.target as HTMLInputElement).value
}

function password(event: Event) {
  console.log(event)
  information.value.password = (event.target as HTMLInputElement).value
}

function password1(event: Event) {
  console.log(event)
  information.value.password1 = (event.target as HTMLInputElement).value
}

function email(event: Event) {
  console.log(event)
  information.value.email = (event.target as HTMLInputElement).value
}

function phone(event: Event) {
  console.log(event)
  information.value.phone = (event.target as HTMLInputElement).value
}

const vision = () => {
  console.log('调用到')
  console.log(flag.value)
  flag.value = !flag.value
  console.log(flag.value)

  if (flag.value) {
    url.value = '../../static/tabs/eye.png'
  } else {
    url.value = '../../static/tabs/眼睛检查.png'
  }
}

// 预览图片
const ViewImage = (e) => {
  uni.previewImage({
    urls: userInfo.value.mid,
    current: e.currentTarget.dataset.url,
  })
}
// 点击图片本地路径
const handleUpImg = (e) => {
  console.log(e.detail, '看看一下')

  console.log('333333333333333333333333')
  // 点击图片区域，选择图片并上传
  uni.chooseImage({
    // 选择图片
    count: 1,
    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album'], //从相册选择
    success: async (res) => {
      console.log('3333333333333333333333331111')

      console.log(res)
      // 图片选择成功的回调（必传），会返回一个对象
      // 用于更新视图
      userInfo.value.mid[0] = res.tempFilePaths[0]

      // 【H5平台，必须将图片类型转为file对象，然后通过file属性上传】
      // #ifdef H5

      const imgBlob = await fetch(res.tempFilePaths[0]).then((r) => r.blob())
      const imgFile = new File([imgBlob], res.tempFiles[0].name, { type: imgBlob.type })
      let form = new FormData()
      form.append('avatarfile', imgFile)
      console.log(imgFile, '这个是什么样111111子')

      // console.log(file)
      // 正式将转好的File对象进行上传
      uni.uploadFile({
        url: `/api/Img`, //改为你的接口
        name: 'avatarfile',
        file: imgFile,
        fileType: 'image',
        success: (res) => {
          userInfo.value.picAddress = res.data
          console.log(res.data, '修改成功')
        },
        header: {
          // 需要带的请求头，token等等
          // 'content-type': 'multipart/form-data',
        },
      })

      // #endif
      // #ifdef MP-WEIXIN
      uni.uploadFile({
        url: '/api/Img', // 请求地址/hospital/user/updateAvatar
        filePath: res.tempFilePaths[0], // 临时文件路径
        name: 'avatarfile', // 文件对应的key值
        header: {
          type: 'client',
          // 需要带的请求头，token等等
          'content-type': 'multipart/form-data',
        },
        formData: {
          // 额外的请求数据
          uesrName: userInfo.value.userName,
        },
        success: (res) => {
          // 成功后的回调
          userInfo.value.picAddress = res.data
          console.log(res.data, '修改成功')
        },
      })
      // #endif
    },
    fail: (err) => {
      console.log(err)

      console.log('555555')
    },
  })
}
const onChooseAvatar = (e) => {
  console.log(666)
  console.log(e.detail)
  // 当点击选择头像按钮时触发此事件，事件参数为e
  const { avatarUrl } = e.detail // 从事件的detail中解构出avatarUrl
  const { uesrName } = userInfo.value // 从userInfo的value中解构出uesrName
  // userInfo.value.picAddress = avatarUrl // 将userInfo中的picAddress赋值为avatarUrl
  // userInfo.value.mid[0] = avatarUrl // 将userInfo中的mid数组的第一个元素赋值为avatarUrl
  information.value.uesrname = uesrName // 将information中的uesrname赋值为uesrName

  console.log('头像变化', avatarUrl)
  uni.uploadFile({
    url: '/api/Img', // 请求地址/hospital/user/updateAvatar
    filePath: avatarUrl, // 临时文件路径
    name: 'avatarfile', // 文件对应的key值
    header: {
      type: 'client',
      // 需要带的请求头，token等等
      'content-type': 'multipart/form-data',
    },
    formData: {
      // 额外的请求数据
      uesrName: userInfo.value.userName,
    },
    success: (res) => {
      // 成功后的回调
      userInfo.value.picAddress = res.data
      userInfo.value.mid[0] = res.data
      console.log(res.data, '修改成功')
    },
  })
}
const member = useMemberStore()
// 提交触发
async function upInfo() {
  // 校验 密码
  let passWord = information.value.password
  let passWord1 = information.value.password1
  if (passWord != passWord1) {
    uni.showToast({
      icon: 'none',
      title: '两次密码不一致~',
    })
    return
  }
  //前端数据请求时，显示加载提示弹框

  // john.doe@example.com
  uni.showLoading({
    title: '加载中...',
  })
  const reg = /^1[3456789]\d{9}$/
  const email =
    /^[A-Za-z0-9]+([-._][A-Za-z0-9]+)*@[A-Za-z0-9]+(-[A-Za-z0-9]+)*(\.[A-Za-z]{2,6}|[A-Za-z]{2,4}\.[A-Za-z]{2,3})$/
  if (reg.test(information.value.phone) && email.test(information.value.email)) {
    // 获取图片路径
    information.value.picAddress = userInfo.value.picAddress
    // 点击上传信息按钮触发的方法
    const bannerList = ref<mylogin>()
    const res = await registerAPIhou(information.value)
    bannerList.value = res.data
    console.log(res)

    // 数据从后端接口返回后，提示弹框关闭
    if (res.code == '1') {
      uni.hideLoading()
      // 成功后跳转到 个人中心
      uni.navigateTo({
        url: '../login/login',
      })
      uni.showToast({
        title: '注册成功',
        //将值设置为 success 或者直接不用写icon这个参数
        icon: 'success',
        //显示持续时间为 2秒
        duration: 3000,
      })
    } else {
      uni.showToast({
        title: '注册错误',
        //将值设置为 success 或者直接不用写icon这个参数
        icon: 'error',
        //显示持续时间为 2秒
        duration: 3000,
      })
    }
  } else {
    uni.showToast({
      title: '校验错误',
      //将值设置为 success 或者直接不用写icon这个参数
      icon: 'error',
      //显示持续时间为 2秒
      duration: 3000,
    })
    return false
  }
}
</script>
<template>
  <view class="user">
    <view class="uni-common-mt">
      <!-- <view class="img-boxs">
        <image :src="userInfo.picAddress" @tap="handleUpImg"> </image>
        <cover-view>修改头像</cover-view>
      </view> -->
      <!-- open-type="chooseAvatar"这个是实现的头像选择功能 -->
      <button
        class="img-boxs"
        open-type="chooseAvatar"
        @chooseavatar="onChooseAvatar"
        @tap="handleUpImg"
      >
        <image :src="userInfo.picAddress"></image>
        <cover-view>修改头像</cover-view>
      </button>
      <button class="bg-img" @tap="ViewImage">预览</button>

      <view class="user-input">
        <view class="title">姓名</view>
        <view class="input">
          <!-- 其实用v-model  等于用@input 和 ：value 这个向子组件传递数据，事件向父组件修改数据   type="nickname"  获取微信的名称-->
          <input
            focus
            type="nickname"
            class=""
            @input="onName"
            :value="information.username"
            maxlength="10"
            placeholder="我们对您的称呼"
          />
        </view>
      </view>

      <view class="user-input">
        <view class="title">密码</view>
        <view class="input">
          <input
            :type="flag ? 'password' : 'text'"
            class=""
            @input="password"
            :value="information.password"
            maxlength="30"
            placeholder="请输入您的密码"
            autocomplete="current-password"
          />
          <image
            :src="url"
            mode="scaleToFill"
            style="width: 50rpx; height: 56rpx; right: -73rpx"
            @tap="vision"
          />
        </view>
      </view>
      <view class="user-input">
        <view class="title"> 确认密码</view>
        <view class="input">
          <input
            :type="flag ? 'password' : 'text'"
            class=""
            @input="password1"
            :value="information.password1"
            maxlength="30"
            placeholder="请确认您的密码"
            autocomplete="current-password"
          />
          <image
            :src="url"
            mode="scaleToFill"
            style="width: 50rpx; height: 56rpx; right: -48rpx"
            @tap="vision"
          />
        </view>
      </view>
      <view class="user-input">
        <view class="title">手机</view>
        <view class="input">
          <input
            class=""
            type="number"
            :value="information.phone"
            maxlength="15"
            @input="bulr"
            placeholder="我们可以成功与您沟通的联系方式"
          />
        </view>
      </view>
      <view v-if="usernameError" class="error-message">{{ usernameError }}</view>
      <view class="user-input">
        <view class="title">邮箱</view>
        <view class="input">
          <input
            class=""
            :value="information.email"
            maxlength="50"
            @input="bulr1"
            placeholder="部分活动进度会以邮箱方式向您告知"
          />
        </view>
      </view>
      <view v-if="passwordError" class="error-message">{{ passwordError }}</view>
    </view>
    <button class="up-button" @click="upInfo()">提交信息</button>
    <view class="notes">
      <p class="aa">
        <span class="aa">*</span
        >您认为不必要的信息可直接忽略，本平台所有信息均用于报名。您发出的名片中只显示您的“姓名、手机、公司、职位和简介”，若涉及您的隐私，请谨慎使用您的名片功能。
      </p>
      <p class="aa">
        <span>*</span
        >信息不全可能无法顺利报名某些展会，为了方便您顺利报名，若报名信息被驳回，您可以随时对个人信息进行修改并再次提交报名信息。
      </p>
    </view>
  </view>
</template>
<style lang="scss">
page {
  background: linear-gradient(to right, rgb(225, 232, 233), rgb(219, 220, 223));
}
.user {
  height: 1000px;
  display: flex;
  /*垂直排列*/
  flex-direction: column;
  align-items: center; /*由于flex-direction: column，因此align-items代表的是水平方向*/
  justify-content: center;
}
.user-input {
  width: 335px;
  height: 50px;
  margin: 20px auto;
  justify-content: center;
  align-items: center;
  display: flex;
  border-style: solid;
  border-color: rgb(240, 228, 228);
  border-width: 1px;
  .input {
    width: 280px;
    margin-left: 20px;
  }
}

.fenjie {
  width: 335px;
  height: 1px;
  background: #ddd;
  margin: 0 auto;
}

.up-button {
  width: 160px;
  height: 40px;
  background: linear-gradient(to right, rgb(0, 225, 255), pink);
  border-radius: 4px;
  font-size: 16px;
  line-height: 40px;
  color: white;
  margin-top: 30px;
}

.notes {
  width: 335px;
  margin: 20px auto 50px;
  font-size: 14px;

  .aa {
    color: red;
    margin-right: 4px;
  }
}

// 本地图片
.img-boxs {
  width: 190rpx;
  height: 210rpx;
  border-radius: 100%;
  position: relative;
  overflow: hidden;
  left: 10rpx;
  top: -20rpx;
}

.img-boxs image {
  width: 100%;
  height: 100%;
  position: absolute;
  border-radius: 100%;
  left: -5rpx;
}

.img-boxs cover-view {
  width: 100px;
  height: 40px;
  text-align: center;
  color: #fff;
  overflow: hidden;
  background-color: rgba(107, 96, 99, 0.4);
  position: absolute;
  left: 50%;
  top: 60%;
  transform: translate(-50%, 0);
}
.bg-img {
  position: relative;
  width: 65px;
  background: linear-gradient(to right, rgb(0, 225, 255), pink);
  left: 0px;
  color: rgb(249, 242, 242);
}
.input {
  display: flex;
  justify-content: center;
}
.input image {
  position: relative;
  right: -15px;
}

.error-message {
  font-size: 20px;
  color: red;
  margin-top: 4px;
}
</style>
